<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/28
 * Time: 下午6:33
 */

namespace EasySwoole\EasySwoole;


use App\Crontab\AddVirtualSignQueue;
use App\Crontab\AutoAddActivity;
use App\Process\RecoverCouponsProcess;
use App\Process\VirtualMultiSignProcess;
use App\Process\VirtualQueuePopProcess;
use App\WebSocket\WebSocketEvent;
use App\WebSocket\WebSocketParser;
use EasySwoole\Component\Process\Manager;
use EasySwoole\EasySwoole\Crontab\Crontab;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\HotReload\HotReload;
use EasySwoole\HotReload\HotReloadOptions;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use EasySwoole\Socket\Dispatcher;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');

        DbManager::getInstance()->addConnection(new Connection(new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'))));

        $redisConfigs = new \EasySwoole\Redis\Config\RedisConfig(\EasySwoole\EasySwoole\Config::getInstance()->getConf('REDIS'));

        \EasySwoole\Pool\Manager::getInstance()->register(new \App\Utility\Pool\RedisPool(new \EasySwoole\Pool\Config(), $redisConfigs), 'redis');
    }

    public static function mainServerCreate(EventRegister $register)
    {
        $register->add($register::onWorkerStart, function () {
            //链接预热
            DbManager::getInstance()->getConnection()->getClientPool()->keepMin();
        });

        // 配置同上别忘了添加要检视的目录
        $hotReloadOptions = new HotReloadOptions;
        $hotReload = new HotReload($hotReloadOptions);
        $hotReloadOptions->setMonitorFolder([EASYSWOOLE_ROOT . '/App']);

        $server = ServerManager::getInstance()->getSwooleServer();
        $hotReload->attachToServer($server);

        /**
         * **************** Crontab任务计划 **********************
         */
        // 开始一个定时任务计划
        Crontab::getInstance()->addTask(AutoAddActivity::class);
        // 开始一个定时任务计划
        Crontab::getInstance()->addTask(AddVirtualSignQueue::class);

        /**
         * **************** Process进程 **********************
         */
//        $recoverCouponsProcessConfig = new \EasySwoole\Component\Process\Config();
//        $recoverCouponsProcessConfig->setProcessName('recoverCouponsProcess'); // 设置进程名称
//        $recoverCouponsProcessConfig->setProcessGroup('Test'); // 设置进程组
////        $recoverCouponsProcessConfig->setArg(['a'=>123]); // 传参
//        $recoverCouponsProcessConfig->setRedirectStdinStdout(false); // 是否重定向标准io
////        $recoverCouponsProcessConfig->setPipeType($processConfig::PIPE_TYPE_SOCK_DGRAM); // 设置管道类型
//        $recoverCouponsProcessConfig->setEnableCoroutine(true); // 是否自动开启协程
//        $recoverCouponsProcessConfig->setMaxExitWaitTime(3); // 最大退出等待时间
//        Manager::getInstance()->addProcess(new RecoverCouponsProcess($recoverCouponsProcessConfig));
//
//        $virtualMultiSignProcess = new \EasySwoole\Component\Process\Config();
//        $virtualMultiSignProcess->setProcessName('virtualMultiSignProcess'); // 设置进程名称
//        $virtualMultiSignProcess->setProcessGroup('Test'); // 设置进程组
////        $virtualMultiSignProcess->setArg(['a'=>123]); // 传参
//        $virtualMultiSignProcess->setRedirectStdinStdout(false); // 是否重定向标准io
////        $virtualMultiSignProcess->setPipeType($processConfig::PIPE_TYPE_SOCK_DGRAM); // 设置管道类型
//        $virtualMultiSignProcess->setEnableCoroutine(true); // 是否自动开启协程
//        $virtualMultiSignProcess->setMaxExitWaitTime(3); // 最大退出等待时间
//        Manager::getInstance()->addProcess(new VirtualMultiSignProcess($virtualMultiSignProcess));

        $virtualQueuePopProcess = new \EasySwoole\Component\Process\Config();
        $virtualQueuePopProcess->setProcessName('virtualQueuePopProcess'); // 设置进程名称
        $virtualQueuePopProcess->setProcessGroup('Test'); // 设置进程组
//        $virtualQueuePopProcess->setArg(['a'=>123]); // 传参
        $virtualQueuePopProcess->setRedirectStdinStdout(false); // 是否重定向标准io
//        $virtualQueuePopProcess->setPipeType($processConfig::PIPE_TYPE_SOCK_DGRAM); // 设置管道类型
        $virtualQueuePopProcess->setEnableCoroutine(true); // 是否自动开启协程
        $virtualQueuePopProcess->setMaxExitWaitTime(3); // 最大退出等待时间
        Manager::getInstance()->addProcess(new VirtualQueuePopProcess($virtualQueuePopProcess));

        /**
         * **************** websocket控制器 **********************
         */
        // 创建一个 Dispatcher 配置
        $conf = new \EasySwoole\Socket\Config();
        // 设置 Dispatcher 为 WebSocket 模式
        $conf->setType($conf::WEB_SOCKET);
        // 设置解析器对象
        $conf->setParser(new WebSocketParser());
        // 创建 Dispatcher 对象 并注入 config 对象
        $dispatch = new Dispatcher($conf);
        // 给server 注册相关事件 在 WebSocket 模式下  message 事件必须注册 并且交给 Dispatcher 对象处理
        $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
            $dispatch->dispatch($server, $frame->data, $frame);
        });
        // 自定义握手
        $websocketEvent = new WebSocketEvent();
        $register->set(EventRegister::onHandShake, function (\swoole_http_request $request, \swoole_http_response $response) use ($websocketEvent) {
            $websocketEvent->onHandShake($request, $response);
        });
        $register->set(EventRegister::onClose, function (\swoole_server $server, int $fd, int $reactorId) use ($websocketEvent) {
            $websocketEvent->onClose($server, $fd, $reactorId);
        });

    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}